package com.insis.registry;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Slf4j
public class NacosUtils {

    private static final String serverAddr = "127.0.0.1:8848";

    private static final NamingService namingService;

    private static InetSocketAddress inetSocketAddress;

    static {
        namingService = getNamingService();
    }

    /**
     * 连接Nacos
     * @return NamingService
     */
    public static NamingService getNamingService() {
        try {
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            return NamingFactory.createNamingService(properties);
        } catch (NacosException e) {
            log.error("连接Nacos错误", e);
        }
        return null;
    }

    /**
     * 服务注册
     * @param name 服务名称
     * @param inetSocketAddress 服务地址
     */
    public static void registerServer(String name, InetSocketAddress inetSocketAddress){
        try {
            namingService.registerInstance(name, inetSocketAddress.getHostName(), inetSocketAddress.getPort());
        } catch (NacosException e) {
            log.error("注册server错误", e);
        }
    }

    /**
     * 获取全部服务实例
     * @param name 服务名称
     * @return 服务实例列表
     */
    public static List<Instance> getAllInstance(String name){
        try {
            return namingService.getAllInstances(name);
        } catch (NacosException e) {
            log.error("获取服务全部实例失败", e);
        }
        return new ArrayList<Instance>();
    }
}
